﻿var j;
var imagesbase = new Array(); //预加载图片
//var canvas = $('#canvas')[0];
var canvas;
var context;
var cengKey, cengKeyText;
var border2 = 0; //判断点击那张图片
var border2_text = 0;
var jsonstr = '';
var textObject = null;
var imgObject = null;
var okchange = false;
//Init();
function downWaterCard(id) {
    $.Jq_Ajax.post({
        url: '/BrokerHome/GetWaterCardModel?demandId=' + id,
        onSuccess: function (res) {
            console.log(res)
            var json = res.Extend.WaterCardConfig;

            jsonstr = JSON.parse(json);
            //jsonstr.background = 'http://bpic.588ku.com/back_pic/05/04/55/685960c007067f0.jpg!r650/fw/800';
            var imgarray = jsonstr.imgarray;
            var textarray = jsonstr.textarray;

            if (imgarray.length > 0) {
                for (var j = 0; j < jsonstr.imgarray.length; j++) {
                    for (var i in res.Extend) {
                        if (jsonstr.imgarray[j].imgN == i) {
                            jsonstr.imgarray[j].imgUrl = res.Extend[i]
                        }
                    }
                }
            }

            if (textarray.length > 0) {
                for (var j = 0; j < jsonstr.textarray.length; j++) {
                    for (var i in res.Extend) {
                        if (jsonstr.textarray[j].textN == "title") {
                            jsonstr.textarray[j].textUrl = res.Extend.CityName + res.Extend.AreaName + res.Extend.Cantavil
                        }

                        if (jsonstr.textarray[j].textN == i) {
                            if (res.Extend[i] == null) {
                                jsonstr.textarray[j].textUrl = "";
                            } else {
                                jsonstr.textarray[j].textUrl = res.Extend[i]
                            }
                        }
                    }
                }

                var totalPorice = '';
                for (var x = 0; x < jsonstr.textarray.length; x++) {
                    if (jsonstr.textarray[x].textN == "Type" && jsonstr.textarray[x].textUrl == "出租") {
                        for (var s = 0; s < jsonstr.textarray.length; s++) {
                            if (jsonstr.textarray[s].textN == "UnitPriceStr") {
                                totalPorice = jsonstr.textarray[s].textUrl;
                                //jsonstr.textarray.splice(s, 1);
                                jsonstr.textarray[s].textUrl = "";
                            }
                            console.log(jsonstr.textarray[s].textN)
                        }
                        for (var z = 0; z < jsonstr.textarray.length; z++) {
                            if (jsonstr.textarray[z].textN == "TotalPriceStr") {
                                jsonstr.textarray[z].textUrl = totalPorice;
                            }
                        }
                    }
                    //if (jsonstr.textarray[x].textN == "TaxPayModeStr" && jsonstr.textarray[x].textUrl == null) {
                    //    jsonstr.textarray.splice(x, 1);
                    //}
                }


            }
            console.log(jsonstr)
            Init(jsonstr)
        }
    })
}

function Init(json) {
    //canvas = $('#canvas')[0];
    canvas = document.createElement('canvas');
    canvas.id = 'canvas';
    canvas.width = 804;
    canvas.height = 1124;
    canvas.style = 'position:absolute;top:-1025451px;left:0;border:1px solid #000;background:#fff;z-index:111111';
    context = canvas.getContext('2d');
    //jsonstr = '{"background":"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1540977271111&di=1d86fa285718d0db97b6e27f579df7b0&imgtype=0&src=http%3A%2F%2Fpic43.photophoto.cn%2F20170526%2F0020033024731032_b.jpg","imgarray":[{"imgX":18.84375,"imgY":154.5,"imgW":359,"imgH":187.33396584440226,"imgN":"main","imgUrl":"http://localhost:2001/style/images/waterCard/demo/main.png"},{"imgX":278.2263562669942,"imgY":438.5,"imgW":100.23478746601165,"imgH":94.45570605787611,"imgN":"code","imgUrl":"http://localhost:2001/style/images/waterCard/demo/code.png"}],"textarray":[{"textX":26.84375,"textY":37,"textW":75,"textH":72,"textN":"typy","color":"#ffffff","textUrl":"售"},{"textX":138.58355377182295,"textY":53,"textW":233.52039245635382,"textH":46,"textN":"title","color":"#ff0080","textUrl":"此处显示房源标题"},{"textX":24.773798602320582,"textY":477.5,"textW":228.4836527953588,"textH":51,"textN":"tel","color":"#400000","textUrl":"此处显示联系电话"}]}';
    jsonstr = json

    textObject = new createText();
    imgObject = new createImage();
    ToastInfoV2("正在生成水牌，请稍等!");
    getcanvas();
    document.body.appendChild(canvas);
    var start1 = setInterval(function () {
        if (okchange) {
            CanvasToImage();
            $('#canvas').remove();
            okchange = false;
            clearInterval(start1);
        }
    }, 800)
}



//文字
//////////////////////
function createText() {
    this.textX = new Array(); //x坐标
    this.textY = new Array(); //y坐标
    this.textW = new Array(); //长度
    this.textH = new Array(); //高度/文字大小
    this.textN = new Array(); //name属性
    this.textF = new Array(); //字体
    this.textWE = new Array(); //文字粗细
    this.textUrl = new Array(); //文字内容
    this.color = new Array();//文字顔色
}
//删除单个文字
createText.prototype.removeWord = function (i) {
    this.textX.splice(i, 1);
    this.textY.splice(i, 1);
    this.textW.splice(i, 1);
    this.textH.splice(i, 1);
    this.textN.splice(i, 1);
    this.textF.splice(i, 1);
    this.textWE.splice(i, 1);
    this.textUrl.splice(i, 1);
    this.color.splice(i, 1);
}
createText.prototype.addText = function (imgsrc, text, width, height, event, name, color, family, weight) {
    var img = new Image();
    var that = this;
    img.crossOrigin = "*";
    img.src = imgsrc;
    that.textUrl.push(text);
    if (event) {
        var pos = windowToCanvas(canvas, event.clientX, event.clientY);
        img.addEventListener("load", function () {
            that.textW.push(width);
            that.textH.push(height);
            that.textX.push(pos.x - width * 0.5);
            that.textY.push(pos.y - height * 0.5);
            that.textN.push(name);
            that.color.push(color);
            that.textF.push(family); //字体
            that.textWE.push(weight); //文字粗细
            drawImage2();
        });
    }
}
createText.prototype.drawText = function (ctx, j) {
    var i, X, Y, W, H, F, WE;
    i = this.textUrl[j];
    X = this.textX[j];
    Y = this.textY[j];
    W = this.textW[j];
    H = this.textH[j];
    F = (typeof (this.textF[j]) != "undefined" && this.textF[j] != "undefined") ? " " + this.textF[j] : ' 黑体'; //字体
    WF = (typeof (this.textWE[j]) != "undefined" && this.textWE[j] != "undefined") ? this.textWE[j] + " " : 'normal '; //文字粗细
    ctx.beginPath();
    ctx.font = WF + H + "px" + F;
    ctx.fillStyle = this.color[j];
    ctx.textAlign = 'left';
    //ctx.fillText(i, X + W / 2, Y + H * 0.87, W);
    ctx.fillText(i, X, Y + H * 0.87, W);
    ctx.restore();
}

//图像
//////////////////////
//////////////////////
function createImage() {
    this.imgX = new Array(); //x坐标
    this.imgY = new Array(); //y坐标
    this.imgW = new Array(); //长度缩放比例
    this.imgH = new Array(); //高度缩放比例
    this.imgN = new Array(); //name属性
    this.imgUrl = new Array(); //图片内容
}
//新增一个图片信息
createImage.prototype.addImg = function (imgsrc, width, height, event, name) {
    var img = new Image();
    var that = this;
    img.crossOrigin = "*";
    img.src = imgsrc;
    that.imgUrl.push(img);
    if (event) {
        var pos = windowToCanvas(canvas, event.clientX, event.clientY);
        img.addEventListener("load", function () {
            that.imgW.push(width);
            that.imgH.push(height);
            that.imgX.push(pos.x - width * 0.5);
            that.imgY.push(pos.y - height * 0.5);
            that.imgN.push(name);
            drawImage2();
        });
    }
}
//画单个图片
createImage.prototype.drawImg = function (ctx, j) {
    var i, X, Y, W, H, r, border;
    i = this.imgUrl[j];
    X = this.imgX[j];
    Y = this.imgY[j];
    W = this.imgW[j];
    H = this.imgH[j];
    ctx.beginPath();
    ctx.drawImage(i, 0, 0, i.width, i.height, X, Y, W, H);
    ctx.stroke();
}
createImage.prototype.removeImg = function (i) {
    this.imgX.splice(i, 1);
    this.imgY.splice(i, 1);
    this.imgW.splice(i, 1);
    this.imgH.splice(i, 1);
    this.imgN.splice(i, 1);
    this.imgUrl.splice(i, 1);
}

//////////////////////////////////
function drawImage2() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.beginPath();
    context.fillStyle = "#fff";
    context.fillRect(0, 0, canvas.width, canvas.height);
    if (imagesbase[0] != undefined) {
        context.drawImage(imagesbase[0], 0, 0, imagesbase[0].width, imagesbase[0].height, 0, 0, canvas.width, canvas.height);
    }
    for (var i = 0; i < imgObject.imgUrl.length; i++) {
        imgObject.drawImg(context, i);
    }
    for (var i = 0; i < textObject.textUrl.length; i++) {
        textObject.drawText(context, i);
    }

    okchange = true;
}

function getcanvas() {
    var images = {};
    var time = 0;
    var json = jsonstr;
    var item = 0;
    $.Jq_Ajax.post({
        url: "/Common/GetPhotosBase64Str",
        data: { ids: json.background },
        onSuccess: function (res) {
            res = res.Extend;
            res = res.replace(/\[|]|"/g, '').split(",");
            var sources = {
                bg: "data:image/jpg;base64," + res[0]
            };
            for (src in sources) {
                images[src] = new Image();
                images[src].crossOrigin = "*";
                images[src].src = sources[src];
                console.info(src);
                images[src].onload = function () {
                    console.info(json.imgarray);
                    var imgarrayI = 0; var imgarrayBool = true;
                    var start2 = setInterval(function () {
                        if (imgarrayI < json.imgarray.length) {
                            if (imgarrayBool) {
                                imgarrayBool = false;
                                $.Jq_Ajax.post({
                                    url: "/Common/GetPhotosBase64Str",
                                    data: { ids: json.imgarray[imgarrayI].imgUrl },
                                    async: false,
                                    onSuccess: function (res) {
                                        res = res.Extend;
                                        res = res.replace(/\[|]|"/g, '').split(",");

                                        var img = new Image();
                                        img.crossOrigin = "*";
                                        img.src = "data:image/jpg;base64," + res[0];
                                        img.onload = function () {
                                            imgObject.imgUrl.push(img);
                                            time++;
                                            imgarrayI++;
                                            imgarrayBool = true;
                                        }
                                        img.onerror = function () {
                                            var img1 = new Image();
                                            img1.crossOrigin = "*";
                                            img1.src = window.location.protocol + "//" + window.location.host+"/default/OFAN.jpg";
                                            img1.onload = function () {
                                                imgObject.imgUrl.push(img1);
                                                time++;
                                                imgarrayI++;
                                                imgarrayBool = true;
                                            }
                                        }
                                    },
                                    onError: function () {
                                        var img1 = new Image();
                                        img1.crossOrigin = "*";
                                        img1.src = window.location.protocol + "//" + window.location.host +"/default/OFAN.jpg";
                                        img1.onload = function () {
                                            imgObject.imgUrl[imgarrayI] = img1;
                                            time++;
                                            imgarrayI++;
                                            imgarrayBool = true;
                                        }
                                    }
                                })
                                imgObject.imgW.push(json.imgarray[imgarrayI].imgW * 2);
                                imgObject.imgH.push(json.imgarray[imgarrayI].imgH * 2);
                                imgObject.imgX.push(json.imgarray[imgarrayI].imgX * 2);
                                imgObject.imgY.push(json.imgarray[imgarrayI].imgY * 2);
                                imgObject.imgN.push(json.imgarray[imgarrayI].imgN);
                            }
                        } else {
                            clearInterval(start2);
                        }
                    }, 800);
                    //for (var i = 0; i < json.imgarray.length; i++) {
                    //    $.Jq_Ajax.post({
                    //        url: "/Common/GetPhotosBase64Str",
                    //        data: { ids: json.imgarray[i].imgUrl },
                    //        async: false,
                    //        onSuccess: function (res) {
                    //            res = res.Extend;
                    //            res = res.replace(/\[|]|"/g, '').split(",");

                    //            var img = new Image();
                    //            img.crossOrigin = "*";
                    //            img.src = "data:image/jpg;base64," + res[0];
                    //            img.onload = function () {
                    //                imgObject.imgUrl[i] = img;
                    //                time++;
                    //            }
                    //            img.onerror = function () {
                    //                var img1 = new Image();
                    //                img1.crossOrigin = "*";
                    //                img1.src = "http://localhost:2001/default/OFAN.jpg";
                    //                img1.onload = function () {
                    //                    imgObject.imgUrl[i] = img1;
                    //                    time++;
                    //                }
                    //            }
                    //        },
                    //        onError: function () {
                    //            imgObject.imgUrl.push("");
                    //            time++;
                    //        }
                    //    })
                    //    imgObject.imgW.push(json.imgarray[i].imgW * 2);
                    //    imgObject.imgH.push(json.imgarray[i].imgH * 2);
                    //    imgObject.imgX.push(json.imgarray[i].imgX * 2);
                    //    imgObject.imgY.push(json.imgarray[i].imgY * 2);
                    //    imgObject.imgN.push(json.imgarray[i].imgN);
                    //}
                }
                imagesbase.push(images[src]);
            }
            console.log(imgObject)

            for (var j = 0; j < json.textarray.length; j++) {

                textObject.textUrl.push(json.textarray[j].textUrl);
                textObject.textW.push(json.textarray[j].textW * 2);
                textObject.textH.push(json.textarray[j].textH * 2);
                textObject.textX.push(json.textarray[j].textX * 2);
                textObject.textY.push(json.textarray[j].textY * 2);
                textObject.textN.push(json.textarray[j].textN);
                textObject.color.push(json.textarray[j].color);
                textObject.textF.push(json.textarray[j].textF);
                textObject.textWE.push(json.textarray[j].textWE);
            }
            var start = setInterval(function () {
                if (time == json.imgarray.length) {
                    drawImage2();
                    clearInterval(start);
                    time = 0;
                }
            }, 800);
        }
    });
}


////////////
function loadImages(sources) {
    var count = 0,
        images = {},
        imgNum = 0;
    for (src in sources) {
        imgNum++;
    }
    for (src in sources) {
        images[src] = new Image();
        images[src].crossOrigin = "*";
        images[src].onload = function () {
            if (++count >= imgNum) {
                imgbool = count;
            }
        }
        images[src].src = sources[src];
        imagesbase.push(images[src]);
    }
}


//画布转图片
function CanvasToImage(event) {
    //drawImage2();
    var img_png_src = canvas.toDataURL("image/png");
    //SaveAs5();
    if (!!window.ActiveXObject || "ActiveXObject" in window) {
        ToastErrorV2("IE不支持该功能噢，请切换极速模式亲~");
        var date = new Date();
        saveFile(img_png_src, date.getHours() + '' + date.getMinutes() + '' + date.getSeconds() + "水牌.png");
    } else {
        var date = new Date();
        saveFile(img_png_src, date.getHours() + '' + date.getMinutes() + '' + date.getSeconds() + "水牌.png");
        ToastSuccessV2("生成成功!。");
    }

    //drawImage2();
}

/**
 * 在本地进行文件保存
 * @param  {String} data     要保存到本地的图片数据
 * @param  {String} filename 文件名
 */
function saveFile(data, filename) {
    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    save_link.href = data;
    save_link.download = filename;

    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    save_link.dispatchEvent(event);
}


//txt文件保存
//function strJsonToJsonByEval() {
//    var tq = this.strJsonToJson();
//    tq = escape(tq); //加密
//    var date = new Date();
//    downloadFile(date.getHours() + '' + date.getMinutes() + '' + date.getSeconds() + "保存码.txt", tq);
//}

//function downloadFile(fileName, content) {
//    var aLink = document.createElement('a');
//    var blob = new Blob([content]);
//    var evt = document.createEvent("HTMLEvents");
//    evt.initEvent("click", false, false); //initEvent 不加后两个参数在FF下会报错
//    aLink.download = fileName;
//    aLink.href = URL.createObjectURL(blob);
//    aLink.dispatchEvent(evt);
//}


function imgTogether(url, sy, callback) {
    var str = [url, sy];
    var canvas = document.createElement('canvas');
    var image = new Image();
    if (url !== undefined) {
        $.Jq_Ajax.post({
            url: "/Common/GetPhotosBase64Str",
            data: { ids: str },
            onSuccess: function (res) {
                res = res.Extend;
                res = res.replace(/\[|]|"/g, '').split(",");
                try {
                    image.src = "data:image/jpg;base64," + res[0];
                    image.crossOrigin = "anonymous";
                    image.onload = function () {
                        var naturalWidth = image.width;
                        var naturalHeight = image.height;
                        var bool = (naturalWidth > naturalHeight);
                        if (bool) {
                            canvas.width = 1500;
                            canvas.height = 1125;
                        } else {
                            canvas.width = 1125;
                            canvas.height = 1500;
                        }
                        var xpos = canvas.width / 2;
                        var ypos = canvas.height / 2;
                        var context = canvas.getContext('2d');

                        // 这是上传图像

                        var imgsy = new Image();
                        imgsy.crossOrigin = "anonymous";
                        imgsy.src = "data:image/png;base64," + res[1];
                        if (bool) {
                            imgsy.onload = function () {
                                // 绘制
                                context.drawImage(image, 0, 0, naturalWidth, naturalHeight, 0, 0, 1500, 1125);
                                context.drawImage(imgsy, 0, 0, imgsy.width, imgsy.height, 0, 0, 1500, 1125);
                                // 回调
                                callback(canvas.toDataURL('image/png'));
                            }
                        } else {
                            context.drawImage(image, 0, 0, naturalWidth, naturalHeight, 0, 0, 1125, 1500);
                            var img2 = new Image();
                            img2.crossOrigin = "anonymous";
                            img2.src = canvas.toDataURL('image/png');
                            img2.onload = function () {
                                var cns = document.createElement('canvas')
                                var cnt = cns.getContext('2d');
                                cns.height = 1125;
                                cns.width = 1500;
                                var xpos1 = cns.width / 2;
                                var ypos1 = cns.height / 2;
                                cnt.save();
                                cnt.translate(xpos1, ypos1);
                                cnt.rotate(90 * Math.PI / 180);
                                cnt.translate(-ypos1, -xpos1);
                                cnt.drawImage(img2, 0, 0, img2.width, img2.height, 0, 0, 1125, 1500);
                                cnt.restore();
                                cnt.drawImage(imgsy, 0, 0, imgsy.width, imgsy.height, 0, 0, 1500, 1125);
                                callback(cns.toDataURL('image/png'));
                            }
                        }
                    }
                } catch (e) {
                    console.info(e);
                    callback(window.location.protocol + "//" + window.location.host + "/default/OFAN.jpg");
                }
            },
            onError: function () {
                callback(window.location.protocol + "//" + window.location.host + "/default/OFAN.jpg");
            }
        });
    }
}

function imgTogetherie8(dom, sy) {
    dom.attr("src", dom.attr("original")).css({ "width": "100%" });
    dom.parent().css({ "position": "relative", "display": "inline-block" });
    var html = "<em style=\"height: {0};width: {1};display: block;position: absolute;top: 0;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='{2}', sizingMethod='scale';\"></em>";
    html = html.format("100%", "100%", sy);
    dom.after($(html));
}